package com.huajin.codetest.base;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadLocal
 * 解决多线程并发问题的工具类
 *
 * ThreadLocalMap
 * 数据结构：数组
 * 解决哈希冲突方法：开放地址法
 * Entry的key是弱引用，value是强引用
 *
 * InheritableThreadLocal
 * 实现父子线程之间的数据传递
 * 线程创建的时候进行复制上下文
 *
 * TransmittableThreadLocal
 * 阿里开源transmittable-thread-local
 * 在线程提交的时候要进行上下文的复制
 *
 *
 * static修饰
 *
 * 线程池
 *
 *
 * 参考：
 * https://juejin.cn/post/6844904151567040519#heading-1
 * https://www.cnblogs.com/hongdada/p/12108611.html
 * https://jingzh.blog.csdn.net/article/details/104980889
 */
public class ThreadLocalTest {

    private static ThreadLocal<Object> threadLocal = new ThreadLocal<>();

//    public static void main(String[] args) {
//        Thread thread = new Thread(() -> {
//            System.out.println("1");
//        });
//        InheritableThreadLocal<Object> inheritableThreadLocal = new InheritableThreadLocal<>();
//
//
//    }

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,1, TimeUnit.MINUTES,new ArrayBlockingQueue<>(1));

        ThreadLocal<Integer> local = new InheritableThreadLocal<>();
        local.set(1);


        executor.execute(()->{
            System.out.println("打印1:"+local.get());
        });

        local.set(2);

        System.out.println("打印2:"+local.get());

        executor.execute(()->{
            System.out.println("打印3:"+local.get());
        });

        executor.shutdown();


//        log("start main...");
//        new Thread(() -> {
//            log("run task...");
//        }).start();
//        new Thread(() -> {
//            log("print...");
//        }).start();
//        log("end main.");
    }

    static void log(String s) {
        System.out.println(Thread.currentThread().getName() + ": " + s);
    }

}
